using Agron.Data.Contracts;
using Agron.Security.ClientLayer;
using Agron.Services.Proxies;

using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.ServiceModel;
using System.Text;
using System.Windows.Forms;


namespace Agron.UI.SmartClient
{
    partial class EditUserInfoForm : Agron.UI.SmartClient.DialogBase
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="EditUserInfoForm"/> class.
        /// </summary>
        public EditUserInfoForm()
        {
            this.InitializeComponent();
        }

        protected override void OnLoadBackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            base.OnLoadBackgroundWorkerDoWork(sender, e);

            using (MembershipServiceProxy membershipService = new MembershipServiceProxy())
            {
                e.Result = membershipService.GetUserProfileByUserName(AgronPrincipal.Current.Identity.Name);
            }
        }

        /// <summary>
        /// Handles the RunWorkerCompleted event of the loadBackgroundWorker control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.ComponentModel.RunWorkerCompletedEventArgs"/> instance containing the event data.</param>
        protected override void OnLoadBackgroundWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            base.OnLoadBackgroundWorkerRunWorkerCompleted(sender, e);

            if (null == e.Error)
            {
                base.bindingSource.DataSource = e.Result;
            }
            else if (e.Error is CommunicationException)
            {
                MessageBoxService.ReportError(this, Properties.Resources.GlobalConnectionFailed);
            }
            else
            {
                if (!ExceptionPolicy.HandleException(e.Error, Constants.SmartClientExceptionPolicy))
                    throw e.Error;
            }
        }

        /// <summary>
        /// Handles the DoWork event of the acceptActionBackgroundWorker control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.ComponentModel.DoWorkEventArgs"/> instance containing the event data.</param>
        protected override void OnAcceptActionBackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            base.OnAcceptActionBackgroundWorkerDoWork(sender, e);

            UserProfile userProfile = (UserProfile) e.Argument;

            using (MembershipServiceProxy membershipService = new MembershipServiceProxy())
            {
                membershipService.UpdateUserProfile(userProfile);
            }
        }
    }
}